<?php
/**
 * Created by PhpStorm.
 * User: a4041
 * Date: 2018/6/22
 * Time: 11:06
 */
namespace App\Http\Controllers\Web;

//header('Access-Control-Allow-Origin:*');

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\UserInfo;
use App\Models\WeixinUser;
use App\Repositories\UserRepository;
use App\Tools\Bank;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Models\CashConfig;
use App\Models\ShopApply;
use Illuminate\Support\Facades\Auth;
//小卢加的，你咬我啊
use Illuminate\Support\Facades\Hash;
use App\Models\UserCheck;

Class UserController extends Controller
{
    protected $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        //$this->middleware('auth');
        $this->userRepository = $userRepository;
    }

    //用户信息
    public function userMessage(Request $request)
    {
        return $this->userRepository->userMessage($request);
    }

    //更改用户信息
    public function updateUserMessage(Request $request)
    {
        if($request->name=='' && $request->avatar=='' && $request->sex==''){
            return show(202,'没有传参');
        }
        return $this->userRepository->updateUserMessage($request);
    }

    //账单明细
    public function account(Request $request)
    {
        return $this->userRepository->account($request->token);
    }

    //账单详情
    public function accountDetail(Request $request)
    {
        $rules = [
            'id' => 'required',
        ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return show(201, $validator->errors()->first());
        }
        return $this->userRepository->accountDetail($request);
    }

    //我的订单
    public function getMyOrder(Request $request)
    {
        $rules = [
            'limit' => 'required|integer',
            'type' => '',
            'page' => 'required|integer',
            'token'=>'string',
        ];
        $message = [
            'token.*'=>'请传递令牌',
            'type.*'=>'订单类型有误',
            'limit.*'=>'错误操作',
            'page.*'=>'错误操作'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201, $validator->errors()->first());
        }
        $type = $request->type;
        if (isset($type)){
            if (!is_numeric($type)){
                return show(201, '订单类型有误');
            }
        }
        return $this->userRepository->getMyOrder($request);
    }

    //订单详情
    public function orderDetail(Request $request)
    {
        $rules = [
            'id' => 'required',
        ];
        $message = [
            'id.*'=>'请使用正确的订单号'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201, $validator->errors()->first());
        }
        return $this->userRepository->orderDetail($request);
    }


    //删除订单
    public function deleteUserOrder(Request $request)
    {
        $rules = [
            'id'=>'required|exists:orders,id',
        ];
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        if(!Auth::id()){
            return show(201,'请先登录');
        }
        $user_id = Auth::id();
        $order = Order::where('id',$request->id)->first();
        if ($order){
            if($user_id != $order->user_id){
                return show(201,'订单不存在');
            }
            if (in_array($order->order_status,[1,-2,-3])){
                $delete = Order::where('id',$request['id'])->delete();
                if($delete){
                    return show('200','订单删除成功');
                }else{
                    return show('201','订单不存在');
                }
            }else{
                return show('201','不允许删除');
            }

        }else{
            return show('201','订单不存在');
        }

    }

    //我的商铺
    public function myShop(Request $request)
    {
        return $this->userRepository->myShop($request->token);
    }

    //商铺收到的订单
    public function ordersReceived()
    {
        return $this->userRepository->ordersReceived();
    }
    
    //提现
    public function withdraw(Request $request)
    {
        $rules = [
            'id' => 'required|exists:cash_configs,id',
            'money'=>'required',
            'token'=>'string'
        ];
        $message = [
            'id.*'=>'请选择正确的提现账号',
            'money.*'=>'请选择正确的金额',
            'token.*'=>'请选择正确令牌'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        return $this->userRepository->withdraw($request);
    }

    //添加银行卡
    public function addCard(Request $request)
    {
        $rules = [
            'account_number' => 'required|unique:cash_configs,account_number',
            'account_user' => 'required',
            'bank'=>'required',
        ];
        $message = [
            'account_number.required'=>'请输入正确银行卡号',
            'account_number.unique'=>'该银行卡已存在',
            'account_user.*'=>'请输入正确姓名',
            'bank.*'=>''
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        $data = [
            'account_number'=>$request->account_number,
            'account_user'=>$request->account_user,
            'bank'=>$request->bank
        ];
        $user_id = Auth::id();
        if(!$user_id){
            return show(203,'请登陆后执行该操作');
        }
        $count = UserInfo::where('user_id',$user_id)->count();
        if ($count != 1){
            return show(202,"请先实名认证");
        }
        $data['user_id'] = $user_id;
        CashConfig::create($data);
        return show('200','银行卡添加成功');
    }

    //删除银行卡
    public function deleteCard(Request $request)
    {

        $rules = [
            'id'=>'required|exists:cash_configs,id',
        ];
        $message = [
            'id.*'=>'请选择正确的银行卡'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        $user_id = Auth::id();
        if(!$user_id){
            return show(203,'请登陆后执行该操作');
        }
        $is_yours = CashConfig::where('user_id',$user_id)->find($request->id);
        if (!$is_yours){
            return show(202,'请选择正确的银行卡');
        }
        $delete = CashConfig::where('id',$request['id'])->delete();
        if($delete){
            return show('200','删除成功');
        }else{
            return show('201','删除失败');
        }
    }

    //展示银行卡
    public function showCard(Request $request)
    {
        $rules = [
            'token'=>'string',
        ];
        $message = [
            'token.*'=>'请传递正确的令牌'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $token = $request->token;
        if($token){
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if($WeixinUser){
                $user_id = $WeixinUser['user_id'];
            }else{
                return show(203,'用户不存在');
            }
            //web端
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(202, '未登录');
            }
        }
        $data = CashConfig::where('status',1)->where('user_id',$user_id)->get();
        if($data->isEmpty()){
            return show('204','empty');
        }
        return show('200','信息获取成功',$data);
    }

    //申请成为商家
    public function applyShop()
    {
        $user_id = Auth::id();
        $data = ShopApply::where('user_id',$user_id)->first();
        if($data) {
            if ($data->status == 0) {
                return show('201', '已申请，请等待审核');
            } else if ($data->status == 1) {
                return show('202', '已通过审核');
            } else if ($data->status == 2) {
                return show('203', '审核不通过，详情请咨询客服');
            }
        }
        ShopApply::create(['user_id'=>$user_id]);
        return show('200','申请成功，请等待审核');
    }


    //设置支付密码
    public function setPayword(Request $request)
    {

        $rules = [
            'payword'=>'required',
            'cpayword' =>'required',
            'token'=>'string'
        ];
        $message = [
            'payword.*'=>'请输入密码',
            'cpayword.*'=>'请输入密码',
            'token.*'=>'请提交令牌'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $token = $request->token;
        if(!$token){//auth验证
            if(!Auth::id())
            {
                return redirect('/login');
            }
            $user_id = Auth::id();
        }else{//token验证

            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show("202","无效token！");
            }else{
                $user= UserCheck::find($WeixinUser->user_id);
                if(!$user){
                    return show("203","用户不存在！");
                }
            }
            $user_id = $WeixinUser->user_id;
        }

        if($request->payword!=$request->cpayword){
            return  show('204','两次密码不一致');
        }
        $setuser = UserCheck::find($user_id);
        if($setuser->payword){
            return show('205','已设置过支付密码');
        }else{
            $setuser->payword = Hash::make($request->payword);
            $setuser->save();
            return show('200','设置成功');
        }

    }

    //修改支付密码
    public function updatePayword(Request $request)
    {
        $rules = [
            'oldPayword'=>'required',
            'newPayword' =>'required',
            'cnewPayword' =>'required',
            'token'=>'string'
        ];
        $message = [
            'oldPayword.*'=>'请输入密码',
            'newPayword.*'=>'请输入密码',
            'cnewPayword.*'=>'请输入密码',
            'token.*'=>'请提交令牌'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $token = $request->token;
        if(!$token){//auth验证
            if(!Auth::id())
            {
                return show('203','未登录');
            }
            $user_id = Auth::id();
        }else{//token验证
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show("202","无效token！");
            }else{
                $user= UserCheck::find($WeixinUser->user_id);
                if(!$user){
                    return show("203","用户不存在！");
                }
            }
            $user_id = $WeixinUser->user_id;
        }
        if($request['newPayword']!=$request['cnewPayword']){
            return  show('201','两次密码不一致');
        }
        $data = UserCheck::find($user_id);
        if(!Hash::check($request['oldPayword'],$data->payword)){
            return show('201','原支付密码错误');
        }
        if(Hash::check($request['newPayword'],$data->payword)){
            return show('201','新密码与旧密码相同');
        }
        $update = array('payword'=>Hash::make($request['newPayword']));
        $res = UserCheck::where('id',$user_id)->update($update);
        if($res){
            return show('200','修改支付密码成功');
        }else{
            return show('204','修改支付密码失败');
        }
    }
    //修改登录密码
    public function updatePassword(Request $request)
    {
        $rules = [
            'oldPassword'=>'required|string',
            'newPassword' =>'required|string|min:6',
            'cnewPassword' =>'required|string|min:6',
        ];
        $message = [
            'oldPassword.*'=>'请填写旧密码',
            'newPassword.*'=>'请填写新密码',
            'cnewPassword.*'=>'请再次填写新密码'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $id = Auth::id();
        if(!$id){
            return redirect('/login');
        }
        if($request['newPassword']!=$request['cnewPassword']){
            return  show(201,'两次密码不一致');
        }
        $data = UserCheck::find($id);
        if(!Hash::check($request['oldPassword'],$data->password)){
            return show(201,'原登录密码错误');
        }
        if(Hash::check($request['newPassword'],$data->password)){
            return show(201,'新密码与旧密码相同');
        }
        $update = array('password'=>Hash::make($request['newPassword']));
        $res = UserCheck::where('id',$id)->update($update);
        if($res){
            return show(200,'修改登录密码成功');
        }else{
            return show(202,'修改登录密码失败');
        }
    }

    // 实名认证
    public function identify(Request $request){
        $rules = [
            'realname'=>'required|string',
            'cardno' =>'required|identitycards|unique:user_infos,id_card',
            'token'=>'string',
        ];
        $message = [
            'realname.*'=>'请填写真实姓名',
            'cardno.unique'=>'该身份证号已经存在',
            'cardno.identitycards'=>'请填写正确的身份证号a',
            'cardno.required'=>'请填写正确的身份证号b',
            'token.*'=>'请提交令牌'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $realName = $request->realname;
        $cardNo = $request->cardno;
        $token = $request->token;
        if(!$token){//auth验证
            if(!Auth::id())
            {
                return redirect('/login');
            }
            $user_id = Auth::id();
        }else{//token验证
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show("201","无效token！");
            }else{
                $user= UserCheck::find($WeixinUser->user_id);
                if(!$user){
                    return show("202","用户不存在！");
                }
            }
            $user_id = $WeixinUser->user_id;
        }
        $count = UserInfo::where('user_id',$user_id)->count();
        if ($count == 1){
            return show("203","该用户已经实名认证！");
        }

        $realName=urlencode($realName);
        $host= "http://1.api.apistore.cn";
        $path = "/idcard";
        $method = "GET";
        $appcode = "359b0e04dd374def9ddcc148bfe586a5";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "cardNo=".$cardNo."&realName=".$realName;
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $result = curl_exec($curl);
        $result = json_decode($result,true);

        try{
            if ($result['error_code'] == '0'){
              UserInfo::create([
                    'user_id'=>$user_id,
                    'real_name'=>$result['result']['realName'],
                    'id_card'=>$result['result']['cardNo']
                ]);
                return show(200,'实名认证成功');
            }else{
                return show(204,'实名认证失败');
            }
        }catch (\Exception $e){
            return show(204,'实名认证失败');
        }
        return show(200,'实名认证成功');

    }
    // 检查是否已经实名认证过了
    public function checkIdentify(Request $request){
        $rules = [
            'token'=>'string',
        ];
        $message = [
            'token.*'=>'请提交令牌'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $token = $request->token;
        if(!$token){//auth验证
            if(!Auth::id())
            {
                return redirect('/login');
            }
            $user_id = Auth::id();
        }else{//token验证
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show("201","无效token！");
            }else{
                $user= UserCheck::find($WeixinUser->user_id);
                if(!$user){
                    return show("202","用户不存在！");
                }
            }
            $user_id = $WeixinUser->user_id;
        }
        $user = DB::table('user_infos')->where('user_id',$user_id)->first();//['id_card as cardNo','real_name as realName']);

        if ($user && ($user->id_card != '')){
            $result['cardNo'] = $user->id_card;
            $result['realName'] = $user->real_name;
            return show(200,'已实名认证',$result);
        }else{
            return show(201,'还未实名认证');
        }

    }
}
